package com.wzy.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述  : 该模式 相当于 但reator单线程，监听 转发 都是在同一线程中进行的，还是容易出现高并发瓶颈，不能发挥处理器多核的优势
 * 创建人:    Wzy
 * 创建时间: 2020-06-10  20:00
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //构造器
    //初始化器
    public GroupChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听
    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        //如果是连接事件
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "上线了");
                        }
                        if (key.isReadable()) {
                            readDate(key);
                        }
                        iterator.remove();
                    }
                } else {
                    System.out.println("没有新连接,等待中");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取客户端发送的消息
    public void readDate(SelectionKey key) {
        //定义socket channel;
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(byteBuffer);
            if (count > 0) {
                String msg = new String(byteBuffer.array()).trim();
                System.out.println("from 客户端:" + msg);

                //想起他服务端转发消息,实现群聊
                sendInfoToOthers(msg, socketChannel);
            }
        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + "离线了");
                key.cancel();
                socketChannel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    //转发消息
    public void sendInfoToOthers(String msg, SocketChannel self) throws IOException {

//        System.out.println("服务器转发消息");

        for (SelectionKey key : selector.keys()) {

            Channel selectableChannel = key.channel();
            if (!(selectableChannel instanceof SocketChannel) || selectableChannel == self) {
                continue;
            }
            SocketChannel channel = (SocketChannel) selectableChannel;
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            try {
                channel.write(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
